import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Test {



    /*
    * 四数之和
    * */
    public static void main(String[] args) {
        int[] nums = {2,2,2,2,2};
        int target = 8;
        System.out.println(fourSum(nums, target));
    }

    public static List<List<Integer>> fourSum(int[] nums, int target) {
        List<List<Integer>> ret = new ArrayList<>();
        //先排序
        Arrays.sort(nums);
        //利用双指针解决问题
        int n = nums.length;
        for (int i = 0; i < n; ) {
            for (int j = i + 1; j < n; ) {
                int left = j + 1;
                int right = n - 1;
                //用long来存储，防止溢出
                long dest = (long)target - nums[i] - nums[j];
                while(left < right){
                    int sum = nums[left] + nums[right];
                    if(sum > dest){
                        right--;
                    } else if (sum < dest) {
                        left++;
                    }else{
                        ret.add((Arrays.asList(nums[i],nums[j],nums[left++],nums[right--])));
                        //缩小区间继续找
//                        left++;
//                        right--;
                        //去重：left、right
                        while(left < right && nums[left] == nums[left - 1]){
                            left++;
                        }
                        while(left < right && nums[right] == nums[right + 1]){
                            right--;
                        }
                    }
                }
                //去重：i、j
                j++;
                while(j < n && nums[j] == nums[j - 1]){
                    j++;
                }
            }
            i++;
            while(i < n && nums[i] == nums[i - 1]){
                i++;
            }
        }
        return ret;
    }


}
